<template>
  <a-modal v-model:visible="modalVisible" @ok="handleOk" @cancel="handleCancel">
    <template #title> 新建发票类型 </template>
    <div>
      <a-form :model="form" ref="formRef" label-align="right" auto-label-width>
        <a-form-item
          :show-colon="true"
          field="typeName"
          label="发票名称"
          required
        >
          <a-input
            placeholder="请输入发票类型名称"
            v-model="form.typeName"
            allow-clear
          ></a-input>
        </a-form-item>
        <a-form-item :show-colon="true" field="taxRate" label="税率" required>
          <a-input-number
            :hide-button="true"
            :min="1"
            placeholder="请输入税率"
            v-model="form.taxRate"
          >
            <template #suffix> % </template></a-input-number
          >
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { reactive, computed, ref, watchEffect } from 'vue';

  const props = withDefaults(
    defineProps<{
      visible: boolean;
    }>(),
    {
      visible: false,
    }
  );
  const formRef = ref();
  const emit = defineEmits(['update:visible', 'addInvoiceEmit']);

  // 判断用户是否显示弹出框
  const modalVisible = computed({
    get() {
      return props.visible;
    },
    set(visible: boolean) {
      emit('update:visible', visible);
    },
  });

  const form = reactive({
    typeName: '',
    taxRate: null,
  });

  const rules = reactive({});

  // 确定
  const handleOk = async () => {
    formRef.value.validate((res) => {
      if (!res) {
        emit('addInvoiceType', form);
        modalVisible.value = false;
      }
    });
  };

  // 取消
  const handleCancel = () => {
    modalVisible.value = false;
  };

  watchEffect(() => {
    form.typeName = '';
    form.taxRate = null;
  });
</script>

<style scoped lang="less"></style>
